package com.dc.pay.controller;


import com.alibaba.fastjson.JSONObject;
import com.dc.base.BaseResponse;
import com.dc.pay.feign.PayContextFeign;
import com.dc.pay.feign.PayMentTransactionInfoFeign;
import com.dc.pay.feign.PaymentChannelFeign;
import com.dc.pay.out.dto.PayMentTransactionDto;
import com.dc.pay.out.dto.PaymentChannelDTO;
import com.dc.web.base.BaseWebController;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author: KEYD
 * @Date: 2020/1/8 20:22
 * @Desc: 简单的测试单点登录
 */
@Controller
public class PayController extends BaseWebController {
    @Autowired
    private PayMentTransactionInfoFeign payMentTransacInfoFeign;

    @Autowired
    private PaymentChannelFeign paymentChannelFeign;

    @Autowired
    private PayContextFeign payContextFeign;

    @RequestMapping("/pay")
    public String pay(@RequestParam("payToken") String payToken, Model model) {
        // 1.验证payToken参数
        if (StringUtils.isEmpty(payToken)) {
            setErrorMsg(model, "支付令牌不能为空!");
            return ERROR_500_FTL;
        }
        // 2.使用payToken查询支付信息
        BaseResponse<PayMentTransactionDto> tokenByPayMentTransac = payMentTransacInfoFeign.tokenByPayMentTransaction(payToken);
        if (!isSuccess(tokenByPayMentTransac)) {
            setErrorMsg(model, tokenByPayMentTransac.getMsg());
            return ERROR_500_FTL;
        }
        // 3.查询支付信息
        PayMentTransactionDto data = tokenByPayMentTransac.getData();
        model.addAttribute("data", data);
        // 4.查询渠道信息
        List<PaymentChannelDTO> paymentChanneList = paymentChannelFeign.selectAll();
        model.addAttribute("paymentChanneList", paymentChanneList);
        model.addAttribute("payToken", payToken);
        return "index";    }


    /**
     * @param payToken
     * @return
     * @throws IOException
     */
    @RequestMapping("/payHtml")
    public void payHtml(String channelId, String payToken, HttpServletResponse response) throws IOException {
        response.setContentType("text/html; charset=utf-8");
        BaseResponse<JSONObject> payHtmlData = payContextFeign.payToHtml(channelId, payToken);
        if (isSuccess(payHtmlData)) {
            JSONObject data = payHtmlData.getData();
            String payHtml = data.getString("payHtml");
            response.getWriter().print(payHtml);
        }
    }
    //    @RequestMapping(value = "/channel")
    //    public String redirect(@RequestParam("channelId") String channelId) {
    //        return "http://localhost:8080/ACPSample_B2C/";
    //    }

}